package demon4;

import java.util.Arrays;

public class MyArrayList implements IList{
    public int UsedSize;
    public int[]elem;
    public MyArrayList() {
        super();
        this.elem=new int[10];
    }
    public boolean isFull(){
        if(UsedSize==elem.length){
            return true;
        }else{
            return false;
        }
    }

    public void ExpansionArrat(){
        Arrays.copyOf(elem,2*elem.length);
    }

    private void checkPosOfAdd(int pos) throws PosNotLegalException{
        if(pos < 0 || pos > UsedSize) {
            throw new PosNotLegalException("pos位置不合法!");
        }
    }
    @Override
    public void add(int data) {
        if(isFull()){
            ExpansionArrat();
        }
        this.elem[UsedSize]=data;
        UsedSize++;
    }

    @Override
    public void add(int pos, int data) {
        if(isFull()){
            ExpansionArrat();
        }
        try {
            checkPosOfAdd(pos);
        }catch (PosNotLegalException e) {
            e.printStackTrace();
        }
        for (int i = UsedSize; i <pos ; i--) {
            this.elem[i+1]=this.elem[i];
        }
        this.elem[pos]=data;
        UsedSize++;
    }

    @Override
    public boolean contains(int toFind) {

        for (int i = 0; i < this.UsedSize; i++) {
            if(this.elem[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i <UsedSize ; i++) {
            if(this.elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        try {
            checkPosOfAdd(pos);
        }catch (PosNotLegalException e) {
            e.printStackTrace();
        }
        return this.elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        try {
            checkPosOfAdd(pos);
        }catch (PosNotLegalException e) {
            e.printStackTrace();
        }
        if(isFull()){
            ExpansionArrat();
        }
        this.elem[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int pos=indexOf(toRemove);
        if(pos==-1){
            System.out.println("没有要找的元素");
            return;
        }
        for (int i = pos; i < UsedSize-1; i++) {
            this.elem[i]=this.elem[i+1];
        }
        UsedSize--;
    }

    @Override
    public int size() {
        return UsedSize;
    }

    @Override
    public void clear() {
        UsedSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i <UsedSize ; i++) {
            System.out.println(this.elem[i]);
        }
    }
}
